package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CacheClient cacheClient;

    //解决缓存穿透问题，采用缓存空值""来解决
    @Override
    public Result queryById(Long id) {
        //现在均调用封装工具类
        //缓存穿透解决方案
//        Shop shop=queryWithPassThrough(id);
//        Shop shop=cacheClient.queryWithPassThrough(CACHE_SHOP_KEY,id,Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);
        //解决缓存击穿问题，采用互斥锁来解决
//        Shop shop=queryWithMutex(id);
        //解决缓存击穿问题，采用逻辑过期方式解决
//        Shop shop=queryWithLogicalExpire(id);
        Shop shop=cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY,id,Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);
        if(shop==null){
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }
    //缓存穿透，击穿均已封装为工具类CacheClient;
    /*
    //创建一个线程池，为后面新建线程进行数据重建
    private  static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);
    //解决缓存击穿问题，采用逻辑过期方式解决
    public Shop queryWithLogicalExpire(Long id) {
        //先尝试从redis中获取店铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //存在则直接返回
        if (StrUtil.isBlank(shopJson)) {
            //由于预热过热点数据，所以其一定是存在的。
            return null;
        }
        //缓存命中后判断缓存是否过期
        //如果过期还会返回过期信息，所以下面判断先做未过期处理
        //先获取对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject shopjson=(JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(shopjson, Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //如果未过期直接返回信息
        if(expireTime.isAfter(LocalDateTime.now())) {
            return shop;
        }
        //如果过期，需要缓存重建
        //缓存重建
        //1.获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        //2.判断是否获得锁
        if(isLock){
           //获得锁后须再次进行检查redis是否已更新为新数据即是否过期，如果未过期则无需重建
            //再次获取缓存
            String shopJson2 = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
            //判断缓存是否过期
            RedisData redisData2 = JSONUtil.toBean(shopJson2, RedisData.class);
            LocalDateTime expireTime2 = redisData2.getExpireTime();
            if(expireTime2.isAfter(LocalDateTime.now())){
                return JSONUtil.toBean(shopjson, Shop.class);
            }
            //3.获得锁则执行查询数据库操作，并将结果缓存到redis中，并返回
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    //直接执行刷新操作
                    this.saveShop2Redis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unlock(lockKey);
                }
            });
        }
        //返回过期的信息
        return shop;
    }

    //解决缓存击穿问题，采用互斥锁来解决
    //互斥锁采用redis的setnx命令实现，当setnx返回1时，表示获取到锁，可以执行查询数据库操作，
    // 当setnx返回0时，表示没有获取到锁，需要等待一段时间后再次尝试获取锁
    public Shop queryWithMutex(Long id){
        //先尝试从redis中获取店铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //存在则直接返回
        if (StrUtil.isNotBlank(shopJson)) {
            //将其反序列化为json字符串
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //判断是否是空值
        if(shopJson!=null){
            return null;
        }
        //到达这里表示缓存未命中，实现缓存重建
        Shop shop= null;
        String lockKey = LOCK_SHOP_KEY + id;
        try {
            //1获取互斥锁
            boolean isLock = tryLock(lockKey);
            //2判断是否获得锁
            if(!isLock){
                //3未获得锁则休眠一会然后重新执行
                 Thread.sleep(50);
                return queryWithMutex(id);
            }
            //3.5获得锁成功应再次检测redis缓存是否存在，存在了则无需进行缓存重建
            String shopJson2= stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
            if(StrUtil.isNotBlank(shopJson)){
                return JSONUtil.toBean(shopJson2, Shop.class);
            }
            //4获得锁则执行查询数据库操作，并将结果缓存到redis中，并返回
            shop = getById(id);
            Thread.sleep(200);
            if (shop==null){
                //5数据库也不存在则返回店铺不存在错误
                //将空值写入redis，并设置过期时间，防止缓存穿透
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "",CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //6存在店铺写入redis
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //7释放互斥锁
            unlock(lockKey);
        }
        return shop;
    }

    //为逻辑过期先进行缓存预存
    public void saveShop2Redis (Long id,Long expireSeconds)throws InterruptedException{
        Thread.sleep(200);
        //1查询店铺数据
        Shop shop = getById(id);
        //2封装逻辑过期
        RedisData redisData=new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //3写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    //获取锁
    public boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(flag);
    }
    //释放锁
    public void unlock(String key){
        stringRedisTemplate.delete(key);
    }*/

    //已经封装为工具类
    //先将上面解决缓存穿透的代码放到下面方法，然后再写解决缓存击穿方法
    /*public Shop queryWithPassThrough(Long id){
        //先尝试从redis中获取店铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //存在则直接返回
        if (StrUtil.isNotBlank(shopJson)) {
            //将其反序列化为json字符串
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        //判断是否是空值
        if(shopJson!=null){
            return null;
        }
        //不存在则查询数据库，将结果缓存到redis中，并返回
        Shop shop=getById(id);
        if (shop==null){
            //数据库也不存在则返回店铺不存在错误
            //将空值写入redis，并设置过期时间，防止缓存穿透
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "",CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }*/

    @Override
    @Transactional
    public Result update(Shop shop) {
        //先更新数据库，再删除缓存
        //先判空
        Long id= shop.getId();
        if(id==null){
            return Result.fail("店铺id不能为空");
        }
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //1 判断是否需要经纬度查询
        if(x==null || y==null){
            //不需要经纬度查询，直接根据类型分页查询
            Page<Shop> page = query().eq("type_id", typeId).page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }
        //2 需要经纬度查询，按照距离排序，分页查询
        int from=(current-1)*SystemConstants.DEFAULT_PAGE_SIZE;
        int end=current*SystemConstants.DEFAULT_PAGE_SIZE;
        //3 从redis查,按照距离排序、分页获取结果
        String key=SHOP_GEO_KEY+typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().//GEOSEARCH key BYLONLAT x y 10 WITHDISTANCE
                search(key, GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
        );
        //4 解析出店铺id
        if(results==null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if(list.size()<=from){
            return  Result.ok(Collections.emptyList());
        }
        Map<String,Distance> map=new HashMap<>(list.size());
        List<Long> ids =new ArrayList<>(list.size());
        //4.1解析出from到end的部分
        list.stream().skip(from).forEach(result->{
            //4.2获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            //4.3 获取距离
            Distance distance = result.getDistance();
            map.put(shopIdStr,distance);
        });
        String str= StrUtil.join(",",ids);
        //5根据店铺id查询店铺数据，并封装返回
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + str + ")").list();
        //6 将距离赋值给shop
        for (Shop shop : shops) {
            shop.setDistance(map.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shops);
    }
}
